package com.gitee.oeoe.hot.refresh;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 自动配置
 *
 * @author oeoe
 * @since jdk1.8+ 2023/1/7
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(HotRefreshProperties.class)
@ConditionalOnProperty(prefix = "mybatis-refresh", name = "enabled", havingValue = "true")
public class HotRefreshConfiguration {
    private final HotRefreshProperties hotRefreshProperties;

    public HotRefreshConfiguration(HotRefreshProperties hotRefreshProperties) {
        this.hotRefreshProperties = hotRefreshProperties;
    }

    @Bean
    public HotRefresh myDateFormatter(SqlSessionFactory sqlSessionFactory) {
        String watchDir = hotRefreshProperties.getWatchDir();
        Boolean enabled = hotRefreshProperties.getEnabled();
        if (null == enabled || !enabled) {
            log.warn("============================ mybatis-refresh not active ====================");
            return null;
        }
        if (null == watchDir) {
            log.error("请指定监控目录。");
            return null;
        }
        Path path = Paths.get(watchDir);
        if (!path.toFile().exists()) {
            log.error("监控目录不存在，请指定监控目录。");
            return null;
        }
        if (!path.toFile().isDirectory()) {
            log.error("监控路径非目录，请指定监控目录。");
            return null;
        }
        return new HotRefresh(sqlSessionFactory, path);

    }
}
